/**
 * webpack dev和prod共同配置使用merge
 * webpack的五大核心
 * entry
 * output
 * loader
 * plugins
 * mode
 */

const path = require("path");
const EslintWebpackPlugin = require("eslint-webpack-plugin"); // ESlint检查
const HtmlWebpackPlugin = require("html-webpack-plugin"); // HTML文件生成
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); // CSS单独提取
const PreloadWebpackPlugin = require("@vue/preload-webpack-plugin"); // prefetch预加载不过浏览器兼容性差

module.exports = {
  entry: "./src/main.js",
  module: {
    rules: [
      {
        // 对每个文件匹配到第一个loader时后面都不匹配了
        oneOf: [
          {
            test: /\.css$/,
            /**
             * loader执行顺序从后往前
             * style-loader作用于js，会阻塞dom加载
             * MiniCssExtractPlugin.loader会将css单独打包用link方式加载，不会阻塞
             * postcss-loader需要在less-loader之前
             */
            use: [MiniCssExtractPlugin.loader, "css-loader"]
          },
          {
            test: /\.less$/,
            use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader", "less-loader"]
          },
          {
            test: /\.(png|jpe?g|svg|gif)/,
            // webpack5内置了file-loader和url-loader
            type: "asset",
            parser: {
              dataUrlCondition: {
                // 小于10kb的转为url-base64编码，稍大点儿1kb左右
                maxSize: 10 * 1024 // 10kb
              }
            },
            generator: {
              filename: "images/[hash-8][ext][query]"
            }
          },
          {
            test: /\.(ttf|woff2?|map3|mp4|avi)/,
            type: "assets/resource",
            generator: {
              filename: "assets/[hash-8][ext][query]"
            }
          },
          {
            test: /\.js$/,
            // exclude: /node_modules/, // 除了node_modules文件夹之外，其他的都处理
            include: path.resolve(__dirname, "../src"), // 只处理src下的文件
            use: [
              {
                loader: "babel-loader",
                options: {
                  cacheDirectory: true, // 开启babel缓存
                  cacheCompression: false // 关闭缓存压缩
                }
              }
            ]
          }
        ]
      }
    ]
  },
  plugins: [
    new EslintWebpackPlugin({
      context: "./src", // 指定文件目录
      exclude: "node_modules", // 默认值
      cache: true, // 开启eslint缓存
      cacheLocation: path.resolve(__dirname, "../node_modules/.cache/eslintcache") // 缓存目录
    }),
    new HtmlWebpackPlugin({
      title: "Webpack5",
      template: path.resolve(__dirname, "../public/index.html")
    }),
    new MiniCssExtractPlugin({
      filename: "css/[name].[contenthash:6].css",
      chunkFilename: "css/[name].chunk.[contenthash:6].css"
    }),
    new PreloadWebpackPlugin({ rel: "prefetch" })
  ]
};
